package com.cxm.qyyz.base.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.cxm.qyyz.R;
import com.cxm.qyyz.base.mvp.BaseContract;
import com.cxm.qyyz.utils.AppUtil;
import com.cxm.qyyz.widget.plus.StatusBarPlus;
import com.trello.rxlifecycle4.LifecycleTransformer;
import com.trello.rxlifecycle4.android.FragmentEvent;


import java.util.List;
import java.util.Objects;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.Layer;
import per.goweii.anylayer.dialog.DialogLayer;

public abstract class BaseLazyLoadFragment<T extends BaseContract.BasePresenter> extends PermissionFragment<T> implements View.OnClickListener {
    View rootView;

    /**
     * 当前Fragment是否首次可见，默认是首次可见
     **/
    private boolean mIsFirstVisible = true;
    /**
     * 当前Fragment的View是否已经创建
     **/
    private boolean isViewCreated = false;
    /**
     * 当前Fragment的可见状态，一种当前可见，一种当前不可见
     **/
    private boolean currentVisibleState = false;

    private Unbinder unbinder;
    protected Activity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutId(), container, false);
            //为fragment根布局设置tag
            rootView.setTag("ContentView");
            //如果有状态栏
            if (supportStatusBar()) {
                rootView = initStatusBar(rootView);
            }
            //是否支持状态控制
//            if (supportStateController()) {
//                statePlus = new StatePlus();
//                statePlus.setOnStateControllerListener(new StatePlus.OnStateControllerListener() {
//                    @Override
//                    public void onStateController(int itemType) {
//                        if (itemType == StatePlus.ERROR) {
//                            onReload();
//                        }
//                    }
//                });
//                rootView = statePlus.init(rootView);
//            }
            unbinder = ButterKnife.bind(this, rootView);
            //注册EventBus
            if (supportEventBus()) {
                registerEventBus();
            }
            initView(rootView);
        }
        isViewCreated = true;//在onCreateView执行完毕，将isViewCreated改为true;

        return rootView;
    }


    protected void registerEventBus() {
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }
    }

    protected void unregisterEventBus() {
//        if (EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().unregister(this);
//        }
    }

    @Override
    public void toast(String message) {
        AppUtil.getInstance().showToast(message);
        dismiss();
    }

    @Override
    public void toast(int resId) {
        AppUtil.getInstance().showToast(resId);
        dismiss();
    }

    @Override
    public void onData() {
//        if (statePlus != null) {
//            statePlus.setState(StatePlus.DATA);
//        }
    }

    @Override
    public void onLoad() {
//        if (statePlus != null) {
//            statePlus.setState(StatePlus.LOAD);
//        }
    }

    @Override
    public void onError() {
//        if (statePlus != null) {
//            statePlus.setState(StatePlus.ERROR);
//        }
    }

    @Override
    public void onReload() {

    }

    @Override
    public void jumpToLogin() {

    }


    protected void releaseEvents() {
        onData();
        onDismiss();
    }
    @Override
    public void onDismiss() {
        dismiss();
    }


    @Override
    public <E> LifecycleTransformer<E> bindToLife() {
        return this.bindUntilEvent(FragmentEvent.DESTROY);
    }

    protected boolean supportEventBus() {
        return false;
    }

    protected boolean supportStateController() {
        return true;
    }

    protected boolean supportStatusBar() {
        return false;
    }


    protected View initStatusBar(View view) {
        view = StatusBarPlus.setColor(view, Color.WHITE);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isViewCreated) {
            if (isVisibleToUser && !currentVisibleState) {//Fragment可见且状态不是可见(从一个Fragment切换到另外一个Fragment,后一个设置状态为可见)
                disPatchFragment(true);
            } else if (!isVisibleToUser && currentVisibleState) {//Fragment不可见且状态是可见(从一个Fragment切换到另外一个Fragment,前一个更改状态为不可见)
                disPatchFragment(false);
            }
        }
    }
    @Override
    public void onShow() {
        showDialog();
    }

    /**
     * 返回子Fragment的布局id
     **/
    public abstract int getLayoutId();

    /**
     * 初始化View的方法
     **/
    public void initView(View rootView) {
    }


    @Override
    public void onStart() {
        super.onStart();

        //isHidden()是Fragment是否处于隐藏状态和isVisible()有区别
        //getUserVisibleHint(),Fragement是否可见
        if (!isHidden() && getUserVisibleHint()) {//如果Fragment没有隐藏且可见
            //执行分发的方法,三种结果对应自Fragment的三个回调，对应的操作，Fragment首次加载，可见，不可见
            disPatchFragment(true);
        }

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
    }

    public void initViews() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!mIsFirstVisible) {
            //表示点击home键又返回操作,设置可见状态为ture
            if (!isHidden() && !getUserVisibleHint() && currentVisibleState) {
                disPatchFragment(true);
            }
        }

    }


    @Override
    public void onPause() {
        super.onPause();
        //表示点击home键,原来可见的Fragment要走该方法，更改Fragment的状态为不可见
        if (!isHidden() && getUserVisibleHint()) {
            disPatchFragment(false);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //当 View 被销毁的时候我们需要重新设置 isViewCreated mIsFirstVisible 的状态
        isViewCreated = false;
        mIsFirstVisible = true;
        releaseEvents();
        if (supportEventBus()) {
            unregisterEventBus();
        }
        unbinder.unbind();
    }


    /**
     * @param visible Fragment当前是否可见，然后调用相关方法
     */
    public void disPatchFragment(boolean visible) {
        String aa = getClass().getSimpleName();
        //如果父Fragment不可见,则不向下分发给子Fragment
//        boolean parentFragmentVsible = isParentFragmentVsible();
//        if (visible && parentFragmentVsible) return;

        // 如果当前的 Fragment 要分发的状态与 currentVisibleState 相同(都为false)我们就没有必要去做分发了。
        if (currentVisibleState == visible) {
            return;
        }

        currentVisibleState = visible;
        if (visible) {//Fragment可见
            if (mIsFirstVisible) {//可见又是第一次
                mIsFirstVisible = false;//改变首次可见的状态
                onFragmentFirst();
            }//可见但不是第一次
            onFragmentVisble();
            //可见状态的时候内层 fragment 生命周期晚于外层 所以在 onFragmentResume 后分发
            dispatchChildFragmentVisibleState(true);
        } else {//不可见
            onFragmentInVisible();
            dispatchChildFragmentVisibleState(false);
        }
    }

    ;


    /**
     * 重新分发给子Fragment
     *
     * @param visible
     */
    private void dispatchChildFragmentVisibleState(boolean visible) {
        FragmentManager childFragmentManager = getChildFragmentManager();
        @SuppressLint("RestrictedApi") List<Fragment> fragments = childFragmentManager.getFragments();
        if (fragments != null) {
            if (!fragments.isEmpty()) {
                for (Fragment child : fragments) {
                    if (child instanceof BaseLazyLoadFragment && !child.isHidden() && child.getUserVisibleHint()) {
                        ((BaseLazyLoadFragment) child).disPatchFragment(visible);
                    }
                }
            }
        }

    }

    //Fragemnet首次可见的方法
    public void onFragmentFirst() {
    }

    //Fragemnet可见的方法
    public void onFragmentVisble() {//子Fragment调用次方法，执行可见操作
    }

    //Fragemnet不可见的方法
    public void onFragmentInVisible() {
    }


    /**
     * 判断多层嵌套的父Fragment是否显示
     */
    private boolean isParentFragmentVsible() {
        BaseLazyLoadFragment fragment = (BaseLazyLoadFragment) getParentFragment();
        return fragment != null && !fragment.getCurrentVisibleState();
    }

    private boolean getCurrentVisibleState() {
        return currentVisibleState;
    }


    //全局定义
    private long lastClickTime = 0L;
    // 两次点击间隔不能少于1000ms
    private static final int FAST_CLICK_DELAY_TIME = 1000;


    @Override
    public void onClick(View view) {
        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
            return;
        }
        lastClickTime = System.currentTimeMillis();
        onClicks(view);
    }

    public void onClicks(View view) {
    }


    DialogLayer dialogLayer;

    /**
     * dialog
     * date 2021/12/20
     * author yzx
     */
    public void showDialog() {
//        if (null == dialogLayer)
//            dialogLayer = (DialogLayer) AnyLayer.dialog(requireActivity())
//                    .contentView(R.layout.item_progressbar)
//                    .gravity(Gravity.CENTER)
//                    .cancelableOnTouchOutside(false)
//                    .cancelableOnClickKeyBack(false)
//                    .bindData(new Layer.DataBinder() {
//                        @Override
//                        public void bindData(@NonNull Layer layer) {
//                            Glide.with(requireActivity())
//                                    .asGif()
//                                    .load(R.drawable.loading)
//                                    .into((ImageView) Objects.requireNonNull(layer.getView(R.id.ivLoad)));
//                        }
//                    });

//        dialogLayer.show();
    }

    /**
     * 取消弹框
     * date 2021/12/20
     * author yzx
     */
    public void dismiss() {
        if (null != dialogLayer) dialogLayer.dismiss();
    }

}